import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import tkinter as tk


def corrn(stock_codes, result_text):
    files = [f'data/{code}.csv' for code in stock_codes]
    # 定义要分析的指标
    indicators = ['收盘','最高', '最低', '开盘', '成交量', '成交额']

    for file in files:
        # 定义最大相关系数和对应的属性
        max_corr = -1
        max_corr_indicator = ''
        df = pd.read_csv(file)
        file_name = df['股票名称'][1]
        # 计算每日收盘价与其他指标的相关系数
        for indicator in indicators:
            if indicators == '收盘':
                continue
            corr = df['收盘'].corr(df[indicator])
            result_text.insert(tk.END, f'{file_name} 中收盘价与 {indicator} 的相关系数为：{corr:.2f}\n')

            # 更新最大相关系数和对应的属性
            if corr > max_corr:
                max_corr = corr
                max_corr_indicator = indicator
        # 打印最大相关系数和对应的属性
        result_text.insert(tk.END, f'股票中与收盘价最相关的属性为：{max_corr_indicator}，最大相关系数为：{max_corr:.2f}\n\n')
        # 计算相关系数矩阵
        corr_matrix = df[indicators].corr()

        sns.set(style='white')
        mask = np.zeros_like(corr_matrix)
        sns.set(font='SimHei', font_scale=1.5)
        mask[np.triu_indices_from(mask)] = True
        fig, ax = plt.subplots(figsize=(10, 8))
        ax = sns.heatmap(corr_matrix, mask=mask, cmap='coolwarm', annot=True, fmt='.2f')
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
        plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
        ax.set_xticklabels(indicators, rotation=45, horizontalalignment='right')
        ax.set_yticklabels(indicators, rotation=0)
        plt.title(f'{file_name}指标相关性热力图')
        plt.show()